/***************************************************
> Copyright (C) 2024 ==KINGYI== All rights reserved.
> File Name: 下午8.5.c
> Author:
> Mail: 
> Created Time: Mon 05 Aug 2024 03:30:49 AM PDT
***************************************************/



//通过消息队列进程a给b发送5个学员，b收到后显示。b给a回送收到消息，a收到后结束。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/msg.h>


typedef struct student
{
	int code;
	char name[10];
	int age;
}STU;

struct msgbuf{
	long mtype;     //消息类型，必须>0
	char  mtext[100]; //消息文本
};
int main(int argc,const char* argv[])
{
	key_t key = 0;
	int msgid = 0;
	int ret = 0;
	key = ftok("./",1);
	if(key == -1)
	{
		perror("ftok");
		exit(-1);
	}

	msgid = msgget(key,IPC_CREAT|0666);
	if(msgid == -1)
	{
		perror("msgget");
		exit(-1);
	}
	struct msgbuf stu;
	memset(&stu,0,sizeof(stu));
	while(1)
	{
		ret = msgrcv(msgid,&stu,sizeof(struct msgbuf)-sizeof(long),1,0);
		if(ret ==-1)
		{
			perror("msgcv");
			exit(-1);
		}
		printf("student is %d\n %s\n %d\n",stu.code,stu.name,stu.age);
		memset(&stu,0,sizeof(stu));
		sleep(1);
	}
	ret = msgsnd(msgid,&msg,sizeof(struct msgbuf)-sizeof(long),0);
	if(ret == -1)
	{
		perror("msgsnd");
		exit(-1);
	}
	printf("stu is %d\n%s\n%d\n",stu.code,stu.name,stu.age);
	ret = msgctl(msgid,IPC_RMID,NULL);
	if(ret == -1)
	{
		perror("msgctl");
		exit(-1);
	}
	return 0;
}
